<?php
class Model_Message extends Df_Model{
	
	private $message_id;
	public function __construct($id = null) {
		$this->message_id = $id;
		parent::__construct(new Model_DbTable_Messages(), $id);
	}
	
	
	public function getMessages($user_id, $page) {
		return $this->_dbTable->fetchAll(
			$this->_dbTable->select()
				->where('user_id = ?',$user_id)
				->limitPage($page, 20)
				->order('date DESC')
			);
	}
	
	public function getUnreadCount($user_id) {
		return $this->_dbTable->fetchAll(
					$this->_dbTable->select()
						->where('user_id = ?',$user_id)
						->where('read_check = ?', '0')
			)->count();
	}
	
	public function setReadMessage($user_id) {
		if($this->checkIfUserMessage($user_id, $this->message_id)){
			$this->_row->read_check = 1;
			$this->_row->save();
		}
	}
	
	public function readMessage($user_id) {
		if($this->checkIfUserMessage($user_id, $this->message_id)){
			//don't know why "!" (NOT) don't work
			$this->_row->read_check = ($this->__get('read_check')==0 ? 1:0);
			$this->_row->save();
		}
	}
	
	public function removeMessage($user_id) {
		if($this->checkIfUserMessage($user_id, $this->message_id)){
			$this->_row->delete();
		}
	}
	
	public function message($user_id) {
		if($this->checkIfUserMessage($user_id, $this->message_id)){
			return $this->_row;
		}
	}
	
	private function checkIfUserMessage($user_id, $message_id) {
		$messCount = $this->_dbTable->fetchRow(
			$this->_dbTable->select()
				->where('user_id =?',$user_id)
				->where('id =?',$this->message_id)
		);
		if($messCount)return true;
		return false;
	}
	
	
	
}